import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';

class FlutterTimePage extends StatefulWidget {
  FlutterTimePage({Key key}) : super(key: key);

  @override
  _FlutterTimePageState createState() => _FlutterTimePageState();
}

class _FlutterTimePageState extends State<FlutterTimePage> {
  DateTime _dateTime = new DateTime.now();
  var _nowTime = TimeOfDay(hour: 12, minute: 30);
  _showDatePicker() async {
    // 方式一
    // showDatePicker(
    //   context: context,
    //   initialDate: _dateTime,
    //   firstDate: DateTime(1980),
    //   lastDate: DateTime(2090),
    // ).then((data) {
    //   print(data); //获取选中的时间
    // });
    // 方式二
    var data = await showDatePicker(
      context: context,
      initialDate: _dateTime,
      firstDate: DateTime(1980),
      lastDate: DateTime(2090),
    );
    // print(data); //获取选中的时间
    setState(() {
      this._dateTime = data;
    });
  }

  _showTimePicker() async {
    var result = await showTimePicker(
      context: context,
      initialTime: _nowTime,
    );
    setState(() {
      this._nowTime = result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter自带时间控件"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text("${formatDate(this._dateTime, [
                      yyyy,
                      '年',
                      mm,
                      '月',
                      dd
                    ])}"),
                    Icon(Icons.arrow_drop_down)
                  ],
                ),
                onTap: this._showDatePicker,
              ),
              InkWell(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text("${_nowTime.format(context)}"),
                    Icon(Icons.arrow_drop_down)
                  ],
                ),
                onTap: this._showTimePicker,
              )
            ],
          )
        ],
      ),
    );
  }
}
